package cn.gztang.controller;

import cn.gztang.constant.ErrorCode;
import cn.gztang.entity.dto.ResultBean;
import cn.gztang.exception.ResultException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 * @author GaoFeng2017
 * @date 2018/7/12 17:37
 */

@ControllerAdvice
public class ExceptionController {
    private Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    /**
     * api接口调用异常处理
     * @author ZengZhengFang
     *
     * @date 2018/7/12 20:51
     *
     * @param resultException
     *
     * @return org.springframework.web.servlet.ModelAndView
     *
     */

    @ExceptionHandler(ResultException.class)
    @ResponseBody
    public Object handleException(ResultException resultException) {
        /*封装错误信息*/
        logger.info(resultException.getMessage());
        return new ResultBean<>(false, resultException.getErrorCode(), resultException.getMessage());
    }

    /**
     * 请求异常处理
     *
     * @author ZengZhengFang
     *
     * @date 2018/7/12 20:52
     *
     * @param e
     *
     * @return org.springframework.web.servlet.ModelAndView
     *
     */
    @ExceptionHandler({HttpMessageNotReadableException.class,TypeMismatchException.class,MissingServletRequestParameterException.class})
    @ResponseBody
    public Object handleRequestException(Throwable e) {
        logger.error(e.getMessage());
        /*封装错误信息到视图对象中*/
        return new ResultBean<>(false, ErrorCode.INVALID_REQUEST_PARAM,"请求参数错误");
    }


}
